package kayao.client.scene.objects;

import javax.microedition.khronos.opengles.GL10;

import kayao.common.Client;
import kayao.client.R;
import kayao.client.scene.PhysicsController;

import com.chopsticks3d.scene.Material;
import com.chopsticks3d.scene.Mesh;
import com.chopsticks3d.scene.MeshNode;
import com.chopsticks3d.scene.Texture;
import com.chopsticks3d.scene.shape.Cube;

/**
* Represents a car in the networked virtual environment.
* It has the name of the owner above it if the owner is not
* the local client, which is the case if the owner is null.
*/
public class CarNode extends MovingEntity {
	private static final Mesh sCarMesh = new Cube();
	
	private MeshNode mCarNode;
	private MeshNode mNameNode;
	private String mName;
	
	// Temporary for moving around
	public float deltaRotation;
	
	private Boolean mPhysicsInitialized = false;
	
	/**
	 * Constructor which set the owner.
	 * @param owner the owner of the entity.
	 */
	public CarNode() {
		this(null);
	}
	
	/**
	 * Constructor which set the owner.
	 * @param owner the owner of the entity.
	 */
	public CarNode(Client owner) {
		super(owner);
		
		if (owner != null) {
			mName = owner.getName();
			
			mNameNode = new CarNameNode(mName);
			mNameNode.setTranslationY(1.5f);
			
			addChild(mNameNode);
		}
		
		// Create the scene of the car
		Material carMaterial = new Material();
		carMaterial.setAmbient(1, 1, 1, 1);
		Texture tex = new Texture(R.drawable.woodbox);
		mCarNode = new MeshNode(sCarMesh, tex, carMaterial);
		mCarNode.setTranslationY(0.5f);
		
		addChild(mCarNode);
	}
	
	@Override
	public void setOwner(Client owner) {
		super.setOwner(owner);
		if (owner != null) {
			mName = owner.getName();
		}
	}
	
	@Override
	public void onDraw(GL10 gl) {
		if (!mPhysicsInitialized) {
			mBodyId = PhysicsController.createDynamicBox(mX, mZ, getScaleX(), getScaleZ(), 0.1f, 0.1f, 0.1f);			
			mPhysicsInitialized = true;
		}
		super.onDraw(gl);
	}
	
	@Override
	public void update() {
		if (this.getBodyId() != -1) {
			PhysicsController.updateBody(this, getBodyId());
		}
		
		super.update();
	}
}
